package com.dm.cloud.common;

import java.io.Serializable;

public class R<T> implements Serializable {

    /**
     *  响应code
     */
    public static final int RESPONSE_SUCCESS_CODE = 0 ;
    public static final int RESPONSE_DEFAULT_FAIL_CODE = 1;

    private T result;
    private String type = "type";
    private String message = "";
    private Integer code = RESPONSE_SUCCESS_CODE;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public void setResult(T result) {
        this.result = result;
    }

    public static <T> R<T> success(T result) {
        return success(result,"成功");
    }

    public static <T> R<T> success(T result, String message) {
        R<T> item = new R<T>();
        item.type = "success";
        item.result = result;
        item.code = RESPONSE_SUCCESS_CODE;
        item.message = message;
        return item;
    }

    public static <T> R<T> success() {
        R<T> item = new R<T>();
        item.type = "success";
        item.result = null;
        item.code = RESPONSE_SUCCESS_CODE;
        item.message = "成功";
        return item;
    }

    public static <T> R<T> failure(String errorCode, String errorMessage) {
        R<T> item = new R<T>();
        item.type = "failure";
        item.code = Integer.valueOf(errorCode);
        item.message = errorMessage;
        return item;
    }

    public static <T> R<T> failure(int errorCode, String errorMessage) {
        R<T> item = new R<T>();
        item.type = "failure";
        item.code = errorCode;
        item.message = errorMessage;
        return item;
    }

    public static <T> R<T> failure(String message) {
        R<T> item = new R<T>();
        item.type = "failure";
        item.code = RESPONSE_DEFAULT_FAIL_CODE;
        item.message = message;
        return item;
    }

    /**
     * 返回R
     *
     * @param data 数据
     * @param <T>  T 泛型标记
     * @return R
     */
    public static <T> R<T> data(T data) {
        return success(data, "操作成功");
    }


    public Integer getCode() {
        return code;
    }

    public T getResult() {
        return result;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String value) {
        this.message = value;
    }

    public void setCode(Integer value) {
        this.code = value;
    }


    @Override
    public String toString() {
        return "[result=" + result + ", message=" + message + ", type=" + type + ", code="
                + code + "]";
    }

}
